﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace Nextensions.Basic
{
    public class DictionaryQueue<TValue>
    {
        private Dictionary<int, int> _dictionary;
        private List<TValue> _list;

        public DictionaryQueue(int capacity)
        {
            _dictionary = new Dictionary<int, int>(capacity);
            _list = new List<TValue>(capacity);
        }

        public void Enqueue(TValue item)
        {
            _list.Add(item);
            _dictionary.Add(item.GetHashCode(), _list.Count - 1);
        }

        public TValue Dequeue()
        {
            TValue item = _list[0];
            Remove(item);

            return item;
        }

        public TValue Peek()
        {
            return _list[0];
        }

        public bool Remove(TValue item)
        {
            int key = item.GetHashCode();
            int index = _dictionary[key];
            _list.RemoveAt(index);

            bool didRemove = _dictionary.Remove(key);

            UpdateIndexes();

            return didRemove;
        }

        public void Clear()
        {
            _list.Clear();
            _dictionary.Clear();
        }

        private void UpdateIndexes()
        {
            foreach(TValue item in _list)
            {
                _dictionary[item.GetHashCode()]--;
            }
        }

        public int Count
        {
            get
            {
                return _list.Count;
            }
        }
    }
}
